package cn.com.dcsgo.filter;

import cn.com.dcsgo.config.WhiteUrlsConfig;
import cn.com.dcsgo.constant.AuthConstant;
import cn.com.dcsgo.constant.BusinessEnum;
import cn.com.dcsgo.constant.HttpConstant;
import cn.com.dcsgo.model.Result;
import com.alibaba.fastjson2.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 身份验证过滤器
 *
 * @author Dcsgo
 * @since 2025/9/16 11:01
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private WhiteUrlsConfig whiteUrlsConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 拿到请求路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        // 在白名单中的直接放行
        if (whiteUrlsConfig.getAllowUrls().contains(path)) {
            return chain.filter(exchange);
        }
        // 其它的要做登陆判断（token是否在Redis中）
        // 前端请求时token是放在请求头中，格式为 Authorization: Bearer xxx
        String authorization = request.getHeaders().getFirst(AuthConstant.AUTHORIZATION);
        if (StringUtils.hasText(authorization)) {
            String token = authorization.replace(AuthConstant.BEARER, "");
            if (StringUtils.hasText(token)) {
                if (stringRedisTemplate.hasKey(AuthConstant.LOGIN_TOKEN_PREFIX + token)) {
                    return chain.filter(exchange);
                }
            }
        }
        // 验证不通过——请求拦截+响应错误信息（未授权）
        log.error("网关拦截请求,请求路径为:{}", path);
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set(HttpConstant.CONTENT_TYPE, HttpConstant.APPLICATION_JSON);
        Result<Object> result = Result.fail(BusinessEnum.UN_AUTHORIZATION);
        String json = JSON.toJSONString(result);
        byte[] bytes = json.getBytes();
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    /**
     * 身份验证过滤器的执行顺序，数字越小，优先级越高
     * @return -1
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
